package cn.ulc.socket.weapp.controller;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import cn.ulc.common.annotation.IgnoreAuth;
import cn.ulc.common.constant.enums.AvailableStatus;
import cn.ulc.common.exception.PlatformException;
import cn.ulc.common.util.AliSmsUtil;
import cn.ulc.common.util.HttpUtil;
import cn.ulc.common.util.Result;
import cn.ulc.socket.weapp.model.dto.MemberDTO;
import cn.ulc.socket.weapp.model.dto.OrderPayDTO;
import cn.ulc.socket.weapp.model.dto.OrderResultDTO;
import cn.ulc.socket.weapp.model.param.BindPhoneParam;
import cn.ulc.socket.weapp.model.param.MemberSaveParam;
import cn.ulc.socket.weapp.model.param.OrderParam;
import cn.ulc.socket.weapp.model.param.UserCouponParam;
import cn.ulc.socket.weapp.service.MemberServ;
import cn.ulc.store.dao.user.MemberRechargeDao;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@RestController
@RequestMapping(value = "/wechat/member")
public class MemberController {
    private static final Log log = LogFactory.get();
    private static Map<String,String> phoneCodeMap = Maps.newHashMap();
    @Autowired
    MemberServ memberServ;
    @GetMapping("/findDetail")
    public Result findDetail(){
        return Result.success(memberServ.findDetail());
    }
    @GetMapping("/findUserCouponList")
    public Result findUserCouponList(String status){
        return Result.success(memberServ.findUserCouponList(status));
    }
    @GetMapping("/findUserCouponDetail/{id}")
    public Result findUserCouponDetail(@PathVariable("id") Long id){
        return Result.success(memberServ.findUserCouponDetail(id));
    }
    //查询订单可用的优惠券
    @PostMapping("/findUserCoupon")
    public Result findUserCoupon(@Validated @RequestBody UserCouponParam param){
        return Result.success(memberServ.findUserCoupon(param));
    }
    //注册会员
    @PostMapping("")
    public Result save(@Validated @RequestBody MemberSaveParam param, BindingResult result){
        if(result.hasErrors()) {
            log.error("保存到购物车信息有误",result.getFieldError().getDefaultMessage());
            return Result.fail(result.getFieldError().getDefaultMessage());
        }
        String code = phoneCodeMap.get(param.getPhone()+"_phone_sms_code");
        if(!param.getCode().equals(code)) throw new PlatformException("验证码错误!");
        OrderResultDTO dto =  memberServ.save(param);
        if(dto!=null){
            phoneCodeMap.remove(param.getPhone()+"_phone_sms_code");
        }
        return Result.success(dto);
    }

    @GetMapping("/sendVerifyCode")
    public Result sendVerifyCode(@Validated String phone){
        String code = RandomUtil.randomNumbers(6);
        try {
            AliSmsUtil.sendVerifyCodeSms(phone,code);
            phoneCodeMap.put(phone+"_phone_sms_code",code);
            return Result.success("ok",true);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail(false);
        }
    }
    @PutMapping("/bindPhone")
    public Result bindPhone(@Validated @RequestBody BindPhoneParam param, BindingResult result){
        if(result.hasErrors()) {
            log.error("修改手机号信息参数错误",result.getFieldError().getDefaultMessage());
            return Result.fail(result.getFieldError().getDefaultMessage());
        }
        String code = phoneCodeMap.get(param.getPhone()+"_phone_sms_code");
        if(!param.getVerifyCode().equals(code)) throw new PlatformException("验证码错误!");
        Boolean isOk =  memberServ.bindPhone(param);
        if(isOk){
            phoneCodeMap.remove(param.getPhone()+"_phone_sms_code");
        }
        return Result.success(isOk);
    }

    /**
     * 订单支付
     */
    @PostMapping("/rechargeToPay")
    public Result rechargeToPay(HttpServletRequest request, @Validated @RequestBody OrderParam param, BindingResult result) {
        if(result.hasErrors()) {
            log.error("登录错误",result.getFieldError().getDefaultMessage());
            return Result.fail(result.getFieldError().getDefaultMessage());
        }
        //获取当前登录用户IP地址
        String ipAddress = HttpUtil.getIpAddress(request);
        log.info("HttpUtil==getIpAddress() :" + ipAddress);
        OrderPayDTO dto = memberServ.orderToPay(ipAddress , param);
        return Result.success(dto);
    }
    //查询会员权益
    @GetMapping("/findMemberPower")
    public Result findMemberPower(){
        return Result.success(memberServ.findMemberPower());
    }

    //续费  创建续费订单
    @PostMapping("/saveMemberRecharge")
    public Result saveMemberRecharge(){
        return Result.success(memberServ.saveMemberRecharge());
    }
}
